package initialization

import (
	"context"
	"go.uber.org/zap"
	"os"
	"seat-service/model"
	"seat-service/model/dto"
	"strconv"
)

func CreateTable() {
	err := DB.AutoMigrate(
		model.Building{},
		model.Campus{},
		model.Classroom{},
		model.Reserve{},
		model.Seat{},
		model.Student{},
		model.Dictionary{},
		model.DictionarySlave{},
		model.Carousel{},
		model.Feedback{},
	)
	if err != nil {
		SeatLogger.Error("register table failed", zap.Error(err))
		os.Exit(0)
	}
	SeatLogger.Info("register table success")

}

func CreateRedis() {
	campus := make([]dto.SeatRedisCampus, 0)
	building := make([]dto.SeatRedisBuilding, 0)
	classroom := make([]dto.SeatRedisClassroom, 0)
	err := DB.Model(&model.Campus{}).Select("id,campus_name").Find(&campus).Error
	if err != nil {
		panic("redis-校区列表导入失败")
	}
	err = DB.Model(&model.Building{}).Select("id,name,campus_id").Find(&building).Error
	if err != nil {
		panic("redis-楼栋列表导入失败")
	}
	err = DB.Model(&model.Classroom{}).Select("id,location,building_id").Find(&classroom).Error
	if err != nil {
		panic("redis-教室列表导入失败")
	}

	c1 := make(map[string]string)
	for _, v := range campus {
		c1[strconv.Itoa(int(v.Id))] = v.CampusName
	}
	b1 := make(map[string]string)
	b11 := make(map[string]string)
	for _, v := range building {
		b1[strconv.Itoa(int(v.Id))] = v.Name
		b11[strconv.Itoa(int(v.Id))] = strconv.Itoa(int(v.CampusId))
	}
	c2 := make(map[string]string)
	c21 := make(map[string]string)
	for _, v := range classroom {
		c2[strconv.Itoa(int(v.Id))] = v.Location
		c21[strconv.Itoa(int(v.Id))] = strconv.Itoa(int(v.BuildingId))
	}
	err = Redis.HSet(context.Background(), "campus-data", c1).Err()
	if err != nil {
		panic("redis-校区列表导入失败:" + err.Error())
	}
	err = Redis.HSet(context.Background(), "building-data", b1).Err()
	err = Redis.HSet(context.Background(), "building-id", b11).Err()
	if err != nil {
		panic("redis-楼栋列表导入失败")
	}
	err = Redis.HSet(context.Background(), "classroom-data", c2).Err()
	err = Redis.HSet(context.Background(), "classroom-id", c21).Err()
	if err != nil {
		panic("redis-教室列表导入失败")
	}
}
